package cn.itcast.filter;

import cn.itcast.domain.Cake;
import cn.itcast.domain.CakeDB;
import cn.itcast.domain.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

//只过滤jsp文件
@WebFilter(filterName = "AutoLoginFilter",urlPatterns = "*.jsp")
public class AutoLoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        System.out.println("------");
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //设置中文
        response.setContentType("text/html; charset=UTF-8");
        HttpSession session = request.getSession();
        String servletPath = request.getServletPath();
        //如果访问的是login.jsp或者register.jsp就直接放行
        if (servletPath.equals("/login.jsp")||servletPath.equals("/register.jsp"))
        {
            chain.doFilter(req, resp);
            return;
        }
        User aa = (User) session.getAttribute("user");

        if (aa==null){
            //自动登录
            System.out.println("正在自动登录");
            autoLogin(request,response);
        }else {
            System.out.println(aa.toString());
        }
        chain.doFilter(req, resp);

    }


    private void autoLogin(HttpServletRequest request,HttpServletResponse response ) throws IOException {
        Cookie[] cookies=request.getCookies();
        if (cookies==null){
            System.out.println("cookies是空");
        }
        String autologin=null;
        for (int i = 0;cookies!=null && i < cookies.length; i++) {

            if ("autologin".equals(cookies[i].getName())){
                //找到指定Cookie
                autologin=cookies[i].getValue();
                System.out.println("找到了");
                break;
            }
        }
        if (autologin!=null){
            //做自动登录
            String[] split = autologin.split("-");
            String username=split[0];
            String password=split[1];
            String c=split[2];
            double yue=Double.parseDouble(c);
            User user=new User(username,password,yue);
            request.getSession().setAttribute("user",user);
            Collection<Cake> cakes = CakeDB.getAll();
            request.getSession().setAttribute("cakes", cakes);
        }else {
            response.sendRedirect(request.getContextPath()+"/login.jsp");
            return;
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
